package com.xb.loan.cashier.alipay.web;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.xb.loan.cashier.alipay.util.*;
import com.xb.loan.cashier.alipay.util.*;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Controller
@Scope("prototype")
public class ChargeAction extends ActionSupport {
    
    @Value("${sign_type}")
    private String sign_type;
    @Value("${md5key}")
    private String md5key;
    
    private String session_key="params";
    
    public String doInit() throws Exception {
        Map<String, String> params = WebUtil.getRequetParams( ServletActionContext.getRequest());
        ActionContext.getContext().getSession().put(session_key, params);
        return "payInit";

    }
  

    public void doPay() throws Exception {
        PrintWriter out = null;
        try {
            final Map<String, String> params = (Map<String, String>)  ActionContext.getContext().getSession().get(session_key);
            params.put("tradeStatus", getTradeStatus());
            String responseHtml = AlipaySubmit.buildSyncResponse(buildSycRetMap(params), "get", "返回商户", params.get("return_url"));
            System.out.println(responseHtml);
            String contentType = "text/html;charset=utf-8";
            ServletActionContext.getResponse().setContentType(contentType);
            out = ServletActionContext.getResponse().getWriter();
            out.print(responseHtml);
            out.flush();
            
            new Thread() {
                public void run() {
                    try {
                        Thread.sleep(2000);
                        AlipaySubmit.buildAsyncResponse(buildAsycRetMap(params), params.get("notify_url"));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                };
            }.start();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            ActionContext.getContext().getSession().remove(session_key);
            if (out != null) {
                out.close();
            }
        }

    }
 

    //同步
    private Map<String, String> buildSycRetMap(Map<String, String> params) {
        Map<String, String> retMap = new HashMap<String, String>();
        retMap.put("is_success", "T");
        retMap.put("sign_type", sign_type);
        retMap.put("service", "alipay.wap.create.direct.pay.by.user");
        //retMap.put("notify_id", "");
        retMap.put("notify_time", UtilDate.getDateFormatter());
        retMap.put("notify_type", "trade_status_sync");
        retMap.put("out_trade_no", params.get("out_trade_no"));
        retMap.put("trade_no", UtilDate.getOrderNum());
        retMap.put("subject", params.get("subject"));

        retMap.put("payment_type", params.get("payment_type"));
        retMap.put("trade_status", params.get("tradeStatus"));
        retMap.put("seller_id", "");

        retMap.put("total_fee", params.get("total_fee"));
        retMap.put("body", "");
        Map<String, String> sParaNew = AlipayCore.paraFilter(retMap);
        String preSignStr = AlipayCore.createLinkString(sParaNew);
        System.out.println("preSignStr="+preSignStr+" md5key="+md5key);
        String sign = MD5.sign(preSignStr, md5key, "utf-8");
        retMap.put("sign", sign);
        return retMap;
    }

    private Map<String, String> buildAsycRetMap(Map<String, String> params) {
        Map<String, String> retMap = new HashMap<String, String>();
        retMap.put("notify_time", UtilDate.getDateFormatter());
        retMap.put("notify_type", "trade_status_async");
      //  retMap.put("notify_id", "");
        retMap.put("sign_type", sign_type);
        retMap.put("out_trade_no", params.get("out_trade_no"));
        retMap.put("trade_no", UtilDate.getOrderNum());
        retMap.put("subject", params.get("subject"));
        retMap.put("payment_type", params.get("payment_type"));
        retMap.put("trade_status", params.get("tradeStatus"));
        retMap.put("total_fee", params.get("total_fee"));
        retMap.put("gmt_create", UtilDate.getDateFormatter());
        retMap.put("gmt_payment", "");
        retMap.put("gmt_close", "");
        retMap.put("seller_email", "");
        retMap.put("buyer_email", "");
        retMap.put("seller_id", "");
        retMap.put("buyer_id", "");
        retMap.put("price", params.get("total_fee"));
        retMap.put("quantity", "1");
        retMap.put("body", "");
        retMap.put("discount", "");
        retMap.put("is_total_fee_adjust", "");
        retMap.put("use_coupon", "");
        retMap.put("refund_status", "");
        retMap.put("refund_status", "");
        Map<String, String> sParaNew = AlipayCore.paraFilter(retMap);
        String preSignStr = AlipayCore.createLinkString(sParaNew);
        System.out.println("preSignStr="+preSignStr+" md5key="+md5key);
        String sign = MD5.sign(preSignStr, md5key, "utf-8");
        retMap.put("sign", sign);
        return retMap;
    }
    
    private String getTradeStatus(){
    	int n = new Random().nextInt(100);
    	if (n>0 && n%2==0) {
			return "TRADE_SUCCESS";
		}
    	return "TRADE_PENDING";
    }
    
}
